package me.firstapp.repository.shop.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.shop.Category;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.shop.CategoryRepository;

@Repository
public class CategoryRepositoryImpl extends EntityRepositoryImpl<Category> implements CategoryRepository {

	@Override
	protected Class<Category> getPersistentClass() {
		return Category.class;
	}

	@Override
	public List<Category> findCategories(Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM Category bean WHERE 1=1 ");

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);

		sql.append(" ORDER BY bean.sort ASC");
		return super.query(Category.class, sql.toString(), parameters);
	}

	@Override
	public Page<Category> findSectionPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Long apiClientId) {
		StringBuilder sql = new StringBuilder(" FROM Category bean where 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		if (searchParams != null) {
			Set<String> keys = searchParams.keySet();
			for (String key : keys) {
				Object value = searchParams.get(key);
				if (value != null) {
					sql.append(" AND bean." + key + " LIKE :value ");
					parameters.put("value", "%" + value + "%");
				}
			}
		}

		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);

		if (StrUtils.isNotNULL(sortParam) && StrUtils.isNotNULL(sortType)) {
			sql.append(" ORDER BY " + sortParam + " " + sortType);
		}

		return super.queryForPage(Category.class, sql.toString(), parameters, pageNo, pageSize);
	}

	@Override
	public Category findCategoryById(Long id, Long apiClientId) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder(" FROM Category bean WHERE 1=1 ");
		
		sql.append(" AND bean.apiClientId =:apiClientId ");
		parameters.put("apiClientId", apiClientId);
		
		sql.append(" AND bean.id =:id ");
		parameters.put("id", id);
		
		List<Category> result = super.query(Category.class, sql.toString(), parameters);
		return result.isEmpty()?null:result.get(0);
	}

}
